package com.xuanyuan.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanyuan.domain.AjaxResult;
import com.xuanyuan.entity.User;
import com.xuanyuan.exception.BusinessException;
import com.xuanyuan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;

@Validated
@Controller
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "redirect:/";
    }

    @ResponseBody
    @GetMapping("/verifyLogin")
    public AjaxResult verifyLogin() {
        return AjaxResult.success("已经登录");
    }

    @ResponseBody
    @PostMapping("/login")
    public AjaxResult getUser(@Validated User user, @NotBlank(message = "密码不能为空") String password, HttpServletRequest request) {
        User oldUser = userService.selectUserByName(user.getUsername());
        //密码摘要算法sha256Hex
        password = DigestUtil.sha256Hex(password.trim());
        if (oldUser == null) {
            return AjaxResult.error("该账号不存在，请先注册");
        } else if (!password.equals(oldUser.getPassword())) {
            return AjaxResult.error("登录失败，账号或密码错误");
        } else {
            request.getSession().setAttribute("user", oldUser);
            //密码脱敏
            oldUser.setPassword(DesensitizedUtil.password(user.getPassword()));
            //返回用户信息给前端
            Map<String, Object> data = new HashMap<>();
            data.put("userInfo", oldUser);
            return AjaxResult.success("登录成功！", data);
        }
    }

    @ResponseBody
    @PostMapping("/register")
    public AjaxResult register(@Validated User user, @NotBlank(message = "密码不能为空") String password, HttpServletRequest request) {
        if (userService.selectUserByName(user.getUsername()) != null) {
            return AjaxResult.error("注册用户失败，用户已存在！");
        }
        //密码摘要算法sha256
        user.setPassword(DigestUtil.sha256Hex(password.trim()));
        //设置普通用户
        user.setStatus("2");
        if (userService.insertUser(user) > 0) {
            User oldUser = userService.selectUserByName(user.getUsername());
            if (oldUser != null) {
                request.getSession().setAttribute("user", oldUser);
                //密码脱敏
                oldUser.setPassword(DesensitizedUtil.password(user.getPassword()));
                //返回用户信息给前端
                Map<String, Object> data = new HashMap<>();
                data.put("userInfo", oldUser);
                return AjaxResult.success("注册并登录成功！", data);
            }
        }
        return AjaxResult.error("注册失败！");
    }

    @ResponseBody
    @PostMapping("/verifyPassword")
    public AjaxResult verifyPassword(@NotBlank(message = "密码不能为空") String password, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        User user = userService.selectUserByName(sessionUser.getUsername());
        //密码摘要算法sha256Hex
        password = DigestUtil.sha256Hex(password.trim());
        if (user == null) {
            return AjaxResult.error("验证失败，该账号不存在");
        } else if (password.equals(user.getPassword())) {
            return AjaxResult.success("验证成功，密码正确");
        } else {
            return AjaxResult.error("验证失败，密码错误");
        }
    }

    @ResponseBody
    @PostMapping("/editPassword")
    public AjaxResult updatePassword(@NotBlank(message = "密码不能为空") String password, @NotBlank(message = "新密码不能为空") String newPassword, HttpServletRequest request) {
        User sessionUser = (User) request.getSession().getAttribute("user");
        User user = userService.selectUserByName(sessionUser.getUsername());
        //密码摘要算法sha256Hex
        password = DigestUtil.sha256Hex(password.trim());
        newPassword = DigestUtil.sha256Hex(newPassword.trim());
        if (user == null) {
            return AjaxResult.error("修改失败，该账号不存在");
        } else if (password.equals(user.getPassword())) {
            User newUser = new User();
            //必须需要id
            newUser.setId(user.getId());
            //修改密码
            newUser.setPassword(newPassword);
            return AjaxResult.toAjax(userService.updateUser(newUser));
        } else {
            return AjaxResult.error("修改失败，旧密码错误");
        }
    }

    @ResponseBody
    @RequestMapping("/page")
    public AjaxResult selectUserPage(User user, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return AjaxResult.success(new PageInfo<>(userService.selectUserList(user)));
    }

    @ResponseBody
    @RequestMapping("/list")
    public AjaxResult selectUserList(User user) {
        return AjaxResult.success(userService.selectUserList(user));
    }

    @ResponseBody
    @PostMapping("/add")
    public AjaxResult insertUser(@Validated User user) {
        if (userService.selectUserByName(user.getUsername()) != null) {
            return AjaxResult.error("添加用户失败，该账号已存在，请换个用户名！");
        } else {
            user.setPassword(DigestUtil.sha256Hex(user.getPassword().trim()));
            return AjaxResult.toAjax(userService.insertUser(user));
        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public AjaxResult updateUser(@Validated User user, @NotNull(message = "用户id不能为空") Integer id) throws BusinessException {
        //必须需要id
        user.setId(id);
        //密码不允许在这里修改
        user.setPassword("");
        return AjaxResult.toAjax(userService.updateUser(user));
    }

    @ResponseBody
    @PostMapping("/removes")
    public AjaxResult deleteUserByIds(@NotEmpty(message = "用户ids不能为空") String[] ids) {
        return AjaxResult.toAjax(userService.deleteUserByIds(ids));
    }
}

